package com.donger.upms.biz.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.upms.api.entity.SysDept;
import com.donger.upms.api.service.ISysDeptService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController extends BaseController {

    private static final String MODULE_NAME = "系统部门管理";

    private final ISysDeptService sysDeptService;

    @GetMapping("tree")
    public Result<List<SysDept>> list() {
        List<SysDept> sysDeptList = sysDeptService.queryList();
        return Res.ok(recursiveBuildTree(sysDeptList, SysDept.LEVEL_ONE_DEPT));
    }

    /**
     * 选择部门(添加、修改菜单)
     */
    @GetMapping("/select")
    public Result select() {
        List<SysDept> deptList = sysDeptService.queryList();
        SysDept root = new SysDept();
        root.setDeptId(0L);
        root.setName("一级部门");
        root.setParentId(-1L);
        deptList.add(root);

        return Res.ok(recursiveBuildTree(deptList, -1L));
    }


    /**
     * 信息
     */
    @GetMapping("/info/{deptId}")
    public Result<SysDept> info(@PathVariable("deptId") Long deptId) {
        SysDept dept = sysDeptService.getById(deptId);
        return Res.ok(dept);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody SysDept dept) {
        return Res.ok(sysDeptService.saveDept(dept));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody SysDept dept) {
        return Res.ok(sysDeptService.updateDeptById(dept));
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{deptId}")
    public Result delete(@PathVariable("deptId") Long deptId) {
        //判断是否有子部门
        List<Long> deptList = sysDeptService.queryDeptIdList(deptId);
        if (deptList.size() > 0) {
            return Res.error("请先删除子部门");
        }
        return Res.ok(sysDeptService.removeDeptById(deptId));
    }

    /**
     * 递归建树
     *
     * @param sysDeptList 查询出的部门数据
     * @param parentId    父节点ID
     * @return 递归后的树列表
     */
    private List<SysDept> recursiveBuildTree(List<SysDept> sysDeptList, Long parentId) {
        List<SysDept> childList = sysDeptList.stream().filter(m -> m.getParentId().equals(parentId)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(childList)) {
            return null;
        }
        for (SysDept sysDept : childList) {
            sysDept.setChildren(recursiveBuildTree(sysDeptList, sysDept.getDeptId()));
        }
        return childList;
    }

}

